//
//  XZDropdownMenu.m
//  XZIBeeBo
//
//  Created by Sean on 16/4/5.
//  Copyright © 2016年 XZSean. All rights reserved.
//

#import "XZDropdownMenu.h"

@interface XZDropdownMenu()

@property (nonatomic, weak) UIImageView *containerView;

@end


@implementation XZDropdownMenu
//懒加载
/**
 *  懒加载只能用强指针
 */
-(UIImageView *)containerView{

    if(!_containerView){
    
        UIImageView *containerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"popover_background"]];
        containerView.width = 217;
        containerView.height = 217;
        containerView.userInteractionEnabled = YES;
        [self addSubview:containerView];
        self.containerView = containerView;
    
    }
    return _containerView;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        
    }
    return self;
}


+(instancetype)dropdownMenu{
 
    return [[self alloc] init];
}


/**
 *  显示控件
 */
- (void)showFrom:(UIView *)from{
    //1.获取屏幕最上面的window窗口
    UIWindow *window  = [[UIApplication sharedApplication].windows lastObject];
    //2.添加自己到window窗口上
    [window addSubview:self];
    //3.设置自己的尺寸等于window的尺寸
    self.frame = window.bounds;
    //4.调整灰色图片的位置
    
    //默认情况下frame是以父控件左上角为坐标原点
    //转换新的坐标系
    /**
     *  from.bounds 是左边from的坐标系按照window来计算
     */
    CGRect newFramr = [from convertRect:from.bounds toView:window];
    //CGRect newFramr = [from.superview convertRect:from.frame toView:window];
 
    self.containerView.y = CGRectGetMaxY(newFramr);
    self.containerView.centerX = CGRectGetMidY(newFramr);
    self.containerView.x = (self.width - self.containerView.width) *.5;
    
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidShow:)]) {
        [self.delegate dropdownMenuDidShow:self];
    }
}
/**
 *  移除控件
 */
- (void)dismiss{

    [self removeFromSuperview];
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidDismiss:)]) {
        [self.delegate dropdownMenuDidDismiss:self];
    }

}

/**
 *  重写set方法
 */
-(void)setContent:(UIView *)content{

    _content = content;
    //设置内容位置
    content.x = 10;
    content.y = 15;
    //调整内容高度
    //content.width = self.containerView.width - 2 * content.x;
    self.containerView.width = CGRectGetMaxX(content.frame) + content.x;
    //设置灰色的宽度
    self.containerView.height = CGRectGetMaxY(content.frame) + content.x;

    
    //添加内容到灰色容器中
    [self.containerView addSubview:content];
}

-(void)setContentController:(UIViewController *)contentController{

    _contentController = contentController;
    //设置控制器的位置
    self.content = contentController.view;

}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
 
    [self dismiss];
}

@end
